/*
 * @Description:
 * @Author: menglong.du
 * @Date: 2021-11-05 13:28:02
 * @LastEditTime: 2022-01-09 16:34:16
 * @LastEditors: menglong.du
 */
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyPlugin = require('copy-webpack-plugin')
const path = require('path')
const webpack = require('webpack')
const fs = require('fs')
// 环境变量注入
let env
try {
	let fileContent = fs.readFileSync(
		path.resolve(
			__dirname,
			`${
				process.env.NODE_ENV === 'production'
					? '.env.production'
					: '.env.development'
			}`
		),
		'utf-8'
	)
	env =
		fileContent.trim() === ''
			? {}
			: fileContent.split('\r\n').reduce((map, item) => {
					let [key, value] = item.split('=')
					map[`process.env.${key}`] = JSON.stringify(value)
					return map
			  }, {})
} catch (error) {
	console.log(error)
}
module.exports = {
	mode: process.env.NODE_ENV === 'production' ? 'production' : 'development',
	entry: './src/index.js',
	output: {
		path: path.join(__dirname, 'dist'),
		filename: 'bundle.js'
	},
	devServer: {
		hot: true,
		port: 3000
	},
	resolve: {
		alias: {
			'@': path.resolve(__dirname, 'src')
		},
		// 加载文件没指定扩展名时找以下扩展名
		extensions: ['.ts', '.tsx', '.js', '.json']
	},
	devtool: 'source-map',
	module: {
		rules: [
			{
				test: /\.js$/,
				exclude: /node_modules/,
				loader: 'babel-loader'
			},
			{
				enforce: 'pre',
				test: /\.(j|t)sx?$/,
				loader: 'source-map-loader'
			},
			{
				test: /\.css$/,
				use: ['style-loader', 'css-loader']
			},
			{
				test: /\.(sa|sc)ss$/,
				use: [
					'style-loader',
					{
						loader: 'css-loader',
						options: { importLoaders: 3, url:false }
					},
					{
						loader: 'postcss-loader',
						options: {
							postcssOptions: {
								plugins: ['autoprefixer']
							}
						}
					},
					'sass-loader'
				]
			},
			{
				test: /\.(jpg|png|gif|svg|jpeg)$/,
				use: ['url-loader']
			}
		]
	},

	plugins: [
		new CopyPlugin({
			patterns: [
				{
					from: '**/*',
					to: path.resolve(__dirname, 'dist/[path]/[name][ext]'),
					context: path.resolve(__dirname, 'public'),
					globOptions: {
						ignore: ['**/*.html', '**/*.ico']
					}
				}
			]
		}),
		new HtmlWebpackPlugin({
			template: './public/index.html',
			favicon: './public/favicon.ico'
		}),
		new webpack.DefinePlugin({
			'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
			...env
		})
	]
}
